package com.itheima.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

/**
 * @author 吴
 * @version V1.0
 * @Description 用户权限认证设置
 * @Package com.itheima.config
 * @date 2021/11/28 14:34
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Reference
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        // 查询用户的信息以及所包含的角色和权限
        User user = userService.findByUsername(username);

        if(user == null){
            logger.error("用户{}不存在", username);
            throw new UsernameNotFoundException("用户名不存在");
        }


        // 添加角色和权限
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();

        Set<Role> roles = user.getRoles();

        roles.stream().forEach(role -> {
            // 角色（必须以 ROLE_ 开头）
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));

            role.getPermissions().stream().forEach(permission -> {
                // 权限
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            });

        });

        return new MyUserConfig(user,authorities);
    }
}
